import React, { useEffect } from 'react';
import {
  Form,
  message,
  Modal,
  Input,
  Button
}
  from 'antd';
import { addTakeAwayGoodRule, getTakeAwayGoodRuleById, updateTakeAwayGoodRule } from '@/services/takeAwayGoodRuleService';
import { getCookie } from '@/utils/cookieUtils';

interface Props {
  modalVisible: boolean;
  onSubmit: () => void;
  onCancel: () => void;
  id?: number;
}

const UpdateModal: React.FC<Props> = (props) => {
  const { modalVisible, onSubmit, onCancel, id } = props;
  const [form] = Form.useForm();
  form.resetFields();

  const saveRecord = async () => {
    form.validateFields().then(async () => {
      console.log(getCookie("shopId"))
      const { StatusCode } = id ? await updateTakeAwayGoodRule({ ...form.getFieldsValue(), Id: id, ShopId: getCookie("shopId") }) : await addTakeAwayGoodRule({ ...form.getFieldsValue(), AddTime: new Date(), ShopId: getCookie("shopId") });
      if ((id && StatusCode == 0) || (!id && StatusCode == 201)) {
        message.success("保存成功！");
        onSubmit?.();
        form.resetFields();
      }
    }).catch(err => console.log(err));
  }

  const getGoodRule = async () => {
    if (!id) {
      return;
    }

    const { Items } = await getTakeAwayGoodRuleById(id, {});
    form.setFieldsValue(Items[0]);
  }

  useEffect(() => {
    getGoodRule();
  }, [id])


  return (
    <Modal
      width={700}
      destroyOnClose
      title="新建"
      open={modalVisible}
      onCancel={() => onCancel()}
      footer={[
        <Button key="submit" onClick={() => { saveRecord() }} type="primary">
          保存
        </Button>,
        <Button key="back" onClick={() => onCancel()} >
          取消
        </Button>,
      ]}
    >
      <Form
        onFinish={saveRecord}
        name="basic"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        style={{ maxWidth: 600 }}
        form={form}
        initialValues={{ remember: true }}
        autoComplete="off"
      >
        <Form.Item label='类别名称' name='Name' rules={[{ required: true }]} ><Input /></Form.Item>

      </Form>
    </Modal>
  );
}

export default UpdateModal;
